package com.wuhuiyue.aop;

import cn.hutool.json.JSONUtil;
import com.wuhuiyue.entity.Log;
import com.wuhuiyue.entity.User;
import com.wuhuiyue.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author hy woo
 * @date 2022/6/14 12:06
 */
@Component
@Aspect
public class MyAspect {

    @Autowired
    HttpServletRequest request;
    @Autowired
    ILogService logService;

    @Before("@annotation(com.wuhuiyue.aop.MyAnn)")
    public void before(JoinPoint joinPoint){
        System.out.println("----- 开始拦截");
        Log log = new Log();
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User){
            String username = ((User) principal).getUsername();
            log.setUsername(username);
        }else {
            log.setUsername("匿名用户");
        }
        log.setIp(request.getRemoteAddr());
        log.setAcesstime(new Date());
        log.setUrlpara(JSONUtil.toJsonStr(joinPoint.getArgs()));
        logService.saveLog(log);
        System.out.println("----- 拦截结束");
    }
}
